package com.xhsd.zlong.generatecode.model.impl.mysql;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.xhsd.zlong.generatecode.model.IColumn;
import com.xhsd.zlong.generatecode.model.IModelFactory;
import com.xhsd.zlong.generatecode.model.ITable;

public class MysqlModelFactory implements IModelFactory {
	private DatabaseUtil databaseUtil;
	
	private MysqlModelFactory(String url, String username,String passwd) throws ClassNotFoundException{
		
		this.databaseUtil=DatabaseUtil.getInstance(url, username, passwd);
		
	}
	
	public static MysqlModelFactory getInstance(String url, String username,String passwd) throws ClassNotFoundException{
		return new MysqlModelFactory(url, username, passwd);
	}

	@Override
	public ITable getTable(String table) throws SQLException {
		//查询出comment信息
		String comment=null;
		
		String showTablesSql="SHOW TABLE STATUS like '"+table+"'";
		
		List<Map<String, Object>> tables = databaseUtil.select(showTablesSql);
		
		comment=(String) tables.get(0).get(MysqlTable.c_comment);

		//查询出列信息
		String showColumnsSql="show full columns from `"+table+"`";

		List<IColumn> columns=new ArrayList<IColumn>();
		
		List<Map<String, Object>> columnMaps = databaseUtil.select(showColumnsSql);
		
		for(Map<String,Object> columnMap:columnMaps){
			
			columns.add(convertMapToColumns(columnMap));
		}
		
		return new MysqlTable(table, comment, columns);
	}
	
	private MysqlColumn convertMapToColumns(Map<String, Object> columnMap) {
		
		return new MysqlColumn((String)columnMap.get(MysqlColumn.c_name), (String)columnMap.get(MysqlColumn.c_type), (String)columnMap.get(MysqlColumn.c_comment),(String) columnMap.get(MysqlColumn.c_key));
	}

	@Override
	public List<ITable> getTables() throws SQLException {
		List<ITable> tables=new ArrayList<ITable>();
		
		//查出所有表
		List<Map<String, Object>> tableMaps = databaseUtil.select(MysqlTable.sql_show_all_tables);
		
		for(Map<String, Object> tableMap:tableMaps){
			
			String table=(String) tableMap.get(MysqlTable.c_name);
			
			tables.add(getTable(table));
			
		}
		
		return tables;
	}

}
